from django.shortcuts import render
from django.views import View
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django import http
from meiduo_mall.utils.response_code import RETCODE
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms


class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成图片文本数据
        text, code, image = captcha.generate_captcha()
        # 保存到redis, redis_cli是临时起的存储容器名字
        redis_cli = get_redis_connection('image_code')
        redis_cli.setex(uuid, constants.IMAGE_CODE_EXPIRES, code)
        # 响应：输出图片数据
        return http.HttpResponse(image, content_type='image/png')


class SmsCodeView(View):
    def get(self, request, mobile):
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')

        # 是否60秒内发送过验证码
        redis_cli_sms = get_redis_connection('sms_code')
        if redis_cli_sms.get(mobile + '_flag') is not None:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '图形验证码频繁发送，请稍候再试'})

        if not all([uuid, image_code]):
            return http.JsonResponse({"code": RETCODE.PARAMERR, "errmsg": "参数不完整"})
        # redis读取出来的数据为bytes类型
        redis_cli = get_redis_connection('image_code')

        image_code_redis = redis_cli.get(uuid)
        if image_code_redis is None:
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码已过期，点击图片换一个"})
        # 删除过期验证码和手机发送标记
        redis_cli.delete(uuid)
        redis_cli_sms.delete(mobile + '_flag')
        # 对比图形验证码 不区分大小写
        if image_code_redis.decode().lower() != image_code.lower():
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码错误"})
        # 生成随机6位数
        sms_code = '%06d' % random.randint(0, 999999)
        # 存入redis
        # redis_cli = get_redis_connection('sms_code')
        # redis_cli.setex(mobile, constants.SMS_CODE_EXPIRES, sms_code)
        # # 储存已发短信的标记
        # redis_cli.setex(mobile+'_flag', constants.SMS_CODE_FLAG, 1)
        # 上面代码优化： 使用管道
        redis_pl = redis_cli_sms.pipeline()
        redis_pl.setex(mobile, constants.SMS_CODE_EXPIRES, sms_code)
        redis_pl.setex(mobile + '_flag', constants.SMS_CODE_FLAG, 1)
        redis_pl.execute()

        # 发短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRES / 60], 1)
        # print(sms_code)
        # 通过delay调用,可以将任务加到队列中，交给celery去执行
        send_sms.delay(mobile, sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})
